package com.websocket.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;


/**
 * @Desc: ----------------
 * @CLASS_NAME: MessageController
 * ----------------
 * @Author: jovi
 * ----------------
 * @Date: 2019-09-02 19:07
 */
@Controller
public class MessageController {

    /**
     * 使用SimpMessagingTemplate 向浏览器发送消息
     */
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * @see MessageMapping 接收/app/hello 的消息
     * @see SendTo 发送给所有客户端，广播形式推送
     * @see org.springframework.messaging.simp.annotation.SendToUser 谁发送过来的，我发送回给谁，点对点形式
     */
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public String broadCast(Message message) {

        byte[] bytes = (byte[]) message.getPayload();

        String string = new String(bytes);

        System.out.println(string);

        //返回给C端的订阅了/topic/greetings的数据
        return "success";
    }


    @MessageMapping("/receive")
    public String receive(Message message) {

        byte[] bytes = (byte[]) message.getPayload();

        String content = new String(bytes);

        String uname = content.split("---")[0];

        System.out.println(uname);

        serverSendMessage2AppointClient(uname);

        return "success";
    }

    /**
     * C端调用此接口，S端再以广播形式发送给订阅了/topic/greetings的C端
     *
     * @return
     */
    @GetMapping("serverSend")
    public String serverSendMessage2Client() {
        //广播形式发送
        simpMessagingTemplate.convertAndSend("/topic/greetings", "我是客户端");
        return "";
    }

    @GetMapping("serverSendAppointClient")
    public void serverSendMessage2AppointClient(String uname) {
        //点对点形式发送
        simpMessagingTemplate.convertAndSendToUser(uname, "/p2p", "我是客户端主动发起");
    }

}
